package dao

import models.Tables._
import org.joda.time.DateTime
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.jdbc.JdbcProfile
import tool.Pojo.QData

import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class SurvExprDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends
  HasDatabaseConfigProvider[JdbcProfile] {


  import utils.MyPostgresProfile.api._

  type MyRow = SurvExprRow
  val table = SurvExpr

  def insert(row: MyRow) = {
    db.run(table += row)
  }

  def insertAll(rows: Seq[MyRow]) = db.run(table ++=
    rows)

  def deleteAll(): Future[Unit] = db.run(table.delete).map(_ => ())

  def getTrueColumnName(x: String) = {
    val r = "([A-Z])".r
    r.replaceAllIn(x, (matcher) =>
      s"_${matcher.group(1).toLowerCase}"
    )
  }

  def selectAll(geneName: String): Future[Seq[MyRow]] = db.run(table.filter(_.gene.toLowerCase === geneName.toLowerCase).result)

  def selectAllGene(qData: QData) = db.run(table.map(_.gene).filter(_.like(s"%${qData.q}%")).distinct.
   result.map(_.toList))

  def selectAllGene = db.run(table.map(_.gene).distinct.result.map(_.toList))

  def selectUniqueValues(keys: List[String]) = {
    val action = DBIO.sequence {
      val rs = keys.map { key =>
        val trueColumnName = getTrueColumnName(key)
        table.map { t =>
          t.getStrColumn(trueColumnName)
        }.distinct.result
      }
      rs
    }
    db.run(action)
  }

}
